

import time
import logging
from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
# 关闭uvicorn日志
logger = logging.getLogger("uvicorn.access")
logger.disabled = True

def mymiddleware(app: FastAPI):
    @app.middleware("http")
    async def add_process_time_header(request, call_next):
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        return response
    @app.middleware("http")
    async def mylogger(request: Request, call_next):
        response = await call_next(request)
        print(f"{request.method} url{request.url} status_code{response.status_code}")
        return response

    app.add_middleware(CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )